package com.studyyang.workmodoul.workqueue;

import com.rabbitmq.client.*;
import com.studyyang.utils.RabbitmqUtils;
import com.studyyang.utils.constant.RabbitMqConstant;

import java.io.IOException;

/**
 *
 * 发送服务1
 *
 * 消息的消费者1
 *
 * @Author yangjin
 * @Description
 * @Date 2021/10/28/23:24
 **/
public class SmsSender1 {

    public static void main(String[] args) throws IOException {
        //获取mq连接
        Connection rabbitMqConn = RabbitmqUtils.getRabbitMqConn();
        //连接信道channel
        Channel channel = rabbitMqConn.createChannel();
        //声明队列
        channel.queueDeclare(RabbitMqConstant.WORK_QUEUE_ORDER_SMS,false,false,false,null);
        //basicQos（int i）,使用该方法就代表mq不在向消费者不断地轮询发送消息了，
        // 而i的含义是：每次推送消息不大于i条，等消费者手里的消息全部消费并确认后，再次接受消息
        channel.basicQos(1);
        //创建消息消费者，进行消息消费
        channel.basicConsume(RabbitMqConstant.WORK_QUEUE_ORDER_SMS,false,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                /*super.handleDelivery(consumerTag, envelope, properties, body);*/
                //将消息的字节数组转换为字符串
                String messageStr = new String(body);
                System.out.println("Sender1-接收到的消息为：" + messageStr);
                //模拟休眠10ms处理业务
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //进行消息的手动确认
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
    }
}
